using System;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace AuthService.Domain.Tokens;

/// <summary>
/// 令牌实体
/// </summary>
public class Token : FullAuditedAggregateRoot<Guid>, IMultiTenant
{
    /// <summary>
    /// 租户ID
    /// </summary>
    public virtual Guid? TenantId { get; set; }

    /// <summary>
    /// 用户ID
    /// </summary>
    public virtual Guid UserId { get; set; }

    /// <summary>
    /// 访问令牌
    /// </summary>
    public virtual string AccessToken { get; set; } = string.Empty;

    /// <summary>
    /// 刷新令牌
    /// </summary>
    public virtual string RefreshToken { get; set; } = string.Empty;

    /// <summary>
    /// 令牌类型
    /// </summary>
    public virtual string TokenType { get; set; } = "Bearer";

    /// <summary>
    /// 客户端ID
    /// </summary>
    public virtual string ClientId { get; set; } = string.Empty;

    /// <summary>
    /// 作用域
    /// </summary>
    public virtual string Scope { get; set; } = string.Empty;

    /// <summary>
    /// 过期时间
    /// </summary>
    public virtual DateTime ExpiresAt { get; set; }

    /// <summary>
    /// 刷新令牌过期时间
    /// </summary>
    public virtual DateTime RefreshExpiresAt { get; set; }

    /// <summary>
    /// 是否活跃
    /// </summary>
    public virtual bool IsActive { get; set; } = true;

    /// <summary>
    /// 撤销时间
    /// </summary>
    public virtual DateTime? RevokedAt { get; set; }

    /// <summary>
    /// 撤销原因
    /// </summary>
    public virtual string RevocationReason { get; set; } = string.Empty;

    protected Token()
    {
    }

    public Token(Guid id, Guid userId, string accessToken, string refreshToken, string clientId) : base(id)
    {
        UserId = userId;
        AccessToken = accessToken;
        RefreshToken = refreshToken;
        ClientId = clientId;
        ExpiresAt = DateTime.Now.AddHours(1);
        RefreshExpiresAt = DateTime.Now.AddDays(30);
    }

    /// <summary>
    /// 检查访问令牌是否过期
    /// </summary>
    public virtual bool IsAccessTokenExpired()
    {
        return DateTime.Now > ExpiresAt;
    }

    /// <summary>
    /// 检查刷新令牌是否过期
    /// </summary>
    public virtual bool IsRefreshTokenExpired()
    {
        return DateTime.Now > RefreshExpiresAt;
    }

    /// <summary>
    /// 撤销令牌
    /// </summary>
    public virtual void Revoke(string reason = "")
    {
        IsActive = false;
        RevokedAt = DateTime.Now;
        RevocationReason = reason;
    }
}